package com.ww.springboot.boot.thread.study.base.lock.aqs.demo.lock2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 简单重入锁 一个线程即使多次获取锁 只需要一次即可解锁 且默认实现为非公平锁:无需进入同步队列 直接获取锁
 *
 * ReentrantLock：重入锁的公平与非公平
 * 1.当前线程获取锁 则无论同步队列是否有线程排队都可以直接获取锁
 * 2.公平与非公平 体现在线程第一次获取锁的是否 如果同步队列
 *
 * @author wanwei
 * @since 2023-03-16 22:07
 */
public class MySimpleReentrantLock implements Lock {

    private MyReentrantSync mySync = new MyReentrantSync();

    @Override
    public void lock() {
        mySync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        mySync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return mySync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return mySync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        mySync.release(1);
    }

    @Override
    public Condition newCondition() {
        return mySync.conditionObject();
    }
}
